/**
 * @description: 发送验证码
 */
import { ref, onUnmounted } from 'vue'
import { sendMobileCode } from '@/api/user'
import { showSuccessToast, type FormInstance, showToast } from 'vant'

export function useSendCode(mobile: string) {
  const code = ref('')
  const form = ref<FormInstance>()
  const time = ref(0)
  let timer: number
  // 发送验证码：验证手机合法性、节流
  const send = async () => {
    // 为空 不执行
    if (!mobile) return showToast('手机号为空！')
    // 不合法 不执行
    await form.value?.validate('mobile')
    // 节流
    // if (time.value > 0) return
    if (timer) return
    try {
      const res = await sendMobileCode(mobile, 'login')
      code.value = res.code
      console.log(code.value)
      showSuccessToast('发送成功')

      time.value = 60
      timer = setInterval(() => {
        time.value--
        if (time.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } catch (err) {
      console.log(err)
    }
  }
  onUnmounted(() => clearInterval(timer))

  return { code, form, time, send }
}
